package servlet;

import dao.UserDao;
import domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
        req.setCharacterEncoding("utf-8");

        //2.获取参数
        //2.1拿到内存中的验证码
        String checkCode = req.getParameter("checkCode");
        User loginUser = new User();
        //2.2获取请求参数

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2.3封装对象
        loginUser.setPassword(password);
        loginUser.setUsername(username);

        //3.先判断验证码是否正确
        //3.1 获取内存中的验证码
        HttpSession session = req.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        //验证码获取后需要立即删除
        session.removeAttribute("checkCode_session");
        //3.2 判断
        if(checkCode_session !=null && checkCode_session.equalsIgnoreCase(checkCode)){
            //将内存中的验证码和用户输入的验证码比较
            //忽略大小写比较
            //判断用户名和密码是否一致
            UserDao dao = new UserDao();
            User user = dao.login(loginUser);
            //成功
            if (user != null) {

                session.setAttribute("user",username);
                //重定向到成功的页面
                resp.sendRedirect(req.getContextPath()+"/success.jsp");

            }
           else {
                //失败
                System.out.println("失败");
                session.setAttribute("login_error","用户名或密码错误");
                //转发到登录页面
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }
        else{
            //验证码不一致
            //存储提示信息到request
            req.setAttribute("cc_error","验证码错误");
            //转发到登录页面
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
